<template>
	<view class="page">

		<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<u--form labelWidth='100' :model="userInfo" :rules="rules" ref="Fform">
			<u-form-item label="出险时间" prop="repairDateString" borderBottom @click="occurrenceModel = true" required>
				<u--input v-model="userInfo.repairDateString" disabled disabledColor="#ffffff" placeholder="请选择出险时间"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="接收信息时间" prop="receiveMsgDateString" borderBottom required
				@click="receiveMsgDateModel = true">
				<u--input v-model="userInfo.receiveMsgDateString" disabled disabledColor="#ffffff"
					placeholder="请选择接收信息时间" border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="报案人" prop="reportPerson" borderBottom required>
				<u--input v-model="userInfo.reportPerson" border="none"></u--input>
			</u-form-item>

			<u-form-item label="车牌号" prop="carId" borderBottom @click="plateShow = true;" required>
				<u--input v-model="userInfo.carId" disabled disabledColor="#ffffff" placeholder="请填写车牌号" border="none">
				</u--input>
				<u-icon slot="right" name="arrow-down"></u-icon>
			</u-form-item>
			<u-form-item label="电话" prop="phone" borderBottom required>
				<u--input v-model="userInfo.phone" border="none" type='number' maxlength="11"></u--input>
			</u-form-item>
			<u-form-item label="保险公司" prop="insCompanyName" borderBottom required @click="insCompanyIdModel(1)">
				<u--input v-model="userInfo.insCompanyName" disabled disabledColor="#ffffff" border="none">
				</u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="性别" prop="sexName" borderBottom @click="showSex = true">
				<u--input v-model="userInfo.sexName" disabled disabledColor="#ffffff" placeholder="请选择性别" border="none">
				</u--input>
				<u-icon slot="right" name="arrow-down"></u-icon>
			</u-form-item>

			<u-form-item label="是否返修" prop="isReturnRepairName" borderBottom @click="showIsReturnRepair= true">
				<u--input v-model="userInfo.isReturnRepairName" disabled disabledColor="#ffffff" placeholder="请选择是否返修"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-down"></u-icon>
			</u-form-item>
			<u-form-item label="出险省" prop="repairProvinceName" borderBottom @click="insCompanyIdModel(2)">
				<u--input v-model="userInfo.repairProvinceName" disabled disabledColor="#ffffff" border="none">
				</u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="出险市" prop="repairCityName" borderBottom @click="insCompanyIdModel(3)">
				<u--input v-model="userInfo.repairCityName" disabled disabledColor="#ffffff" border="none">
				</u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="出险地点" prop="repairAddress" borderBottom required>
				<u--input v-model="userInfo.repairAddress" border="none"></u--input>
			</u-form-item>
			<u-form-item label="线索类型" prop="clueType" required borderBottom @click="showClueType = true">

				<u--input v-model="userInfo.clueType" disabled disabledColor="#ffffff" placeholder="请选择线索类型"
					border="none">
				</u--input>
				<u-icon slot="right" name="arrow-down"></u-icon>
			</u-form-item>
			<u-form-item label="线索创建人" prop="clueCreatePerson" borderBottom>
				<u--input v-model="userInfo.clueCreatePerson" border="none" disabled></u--input>
			</u-form-item>

			<u-form-item label="是否到店" prop="isInStoreName" borderBottom @click="showisInStore= true">
				<u--input v-model="userInfo.isInStoreName" disabled disabledColor="#ffffff" placeholder="请选择是否到店"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-down"></u-icon>
			</u-form-item>



			<u-form-item label="报案号" prop="reportNo" borderBottom>
				<u--input v-model="userInfo.reportNo" border="none"></u--input>
			</u-form-item>




			<u-form-item label="线索来源" prop="sourcesClues" borderBottom @click="sourcesCluesShow = true" required>
				<u--input v-model="userInfo.sourcesClues" disabled disabledColor="#ffffff" placeholder="请选择线索来源"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-down"></u-icon>
			</u-form-item>

			<u-form-item label="图片上传" required>
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					@oversize="oversize" :maxSize="2*1024*1024" :sizeType="['compressed']" :maxCount="5">
				</u-upload>
			</u-form-item>


			<u-form-item label="备注" prop="clueRemark">
				<u--textarea v-model="userInfo.clueRemark" placeholder="请输入内容"></u--textarea>
			</u-form-item>
		</u--form>
		<u-button type='primary' @click="submit">提交</u-button>
		<u-action-sheet :show="showSex" :actions="actions" title="请选择性别" @close="showSex = false" @select="sexSelect" />
		<u-action-sheet :show="showClueType" :actions="listClueType" title="请选择线索" @close="showClueType = false"
			@select="clueTypeSelect" />
		<u-action-sheet :show="showIsReturnRepair" :actions="typeRepair" title="请选择是否返修"
			@close="showIsReturnRepair = false" @select="isReturnRepairSelect" />
		<u-action-sheet :show="showisInStore" :actions="type" title="请选择是否到店" @close="showisInStore = false"
			@select="isInStoreSelect" />
		<u-calendar :show="occurrenceModel" mode="single" @confirm="confirmOccurrence" @close='occurrenceModel=false'
			closeOnClickOverlay />


		<u-action-sheet :show="sourcesCluesShow" :actions="listClueSources" title="请选择请选择线索来源"
			@close="sourcesCluesShow = false" @select="sourcesCluesSelect" />



		<u-calendar :show="receiveMsgDateModel" mode="single" @confirm="confirmReceiveMsgDate"
			@close='receiveMsgDateModel=false' closeOnClickOverlay />


		<plate-input v-if="plateShow" :plate="userInfo.carId" @export="setPlate" @close="plateShow = false"
			@transfer="getUser" />
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import plateInput from '@/common/components/uni-plate-input/uni-plate-input.vue';
	import store from '@/store/index.js';
	import {
		pathToBase64,
		base64ToPath
	} from 'pagesA/common/main/base64.js'
	var lists;
	var userData = {
		companyCode: '', //门店键
		userCode: '', //门店键
		clueId: '',
		repairDateString: '', //出险时间
		receiveMsgDateString: '', //接收信息时间
		reportPerson: '', //报案人
		sex: '', //性别
		sexName: '', //性别页面展示
		carId: '', //车牌号
		isNewEnergy: 7, //是否新能源
		phone: '', //手机号
		insCompanyId: '', //保险公司id
		insCompanyName: '', //保险公司name
		isReturnRepair: '', //是否返修
		isReturnRepairName: '', //是否返修name
		repairProvinceName: '', //出险省名字
		repairProvince: '', //出险省id
		regionCode: '', //出险省接口id
		repairCityName: '', //出险市名字
		repairCity: '', //出险市id
		repairAddress: '', //出险地点
		clueCreatePerson: '', //线索创建人
		clueType: '', //跟踪人
		isInStore: '', //是否到店
		isInStoreName: '', //是否到店name
		clueRemark: '', //备注
		// clueType: '', //线索类型
		reportNo: "",
		sourcesClues: "",
		sourcesCluesId: ""
	}

	var newImgListN = []
	export default {
		components: {
			plateInput
		},
		data() {
			var phoneRule = (rule, value, callback) => {
				if (this.validatePhone(value)) {
					callback()
				} else {
					callback(new Error('请正确输入手机号码'))
				}
			}
			return {
				occurrenceModel: false, //出险时间弹框
				receiveMsgDateModel: false, //接收信息时间弹窗
				showSex: false, //性别
				plateShow: false, //车牌号弹框
				showisInStore: false, //是否到店
				showIsReturnRepair: false, //是否返修
				showClueType: false, //线索类型
				sourcesCluesShow: false, //线索来源
				userInfo: {
					companyCode: '', //门店键
					userCode: '', //门店键
					clueId: '',
					repairDateString: '', //出险时间
					receiveMsgDateString: '', //接收信息时间
					reportPerson: '', //报案人
					sex: '', //性别
					sexName: '', //性别页面展示
					carId: '', //车牌号
					isNewEnergy: 7, //是否新能源
					phone: '', //手机号
					insCompanyId: '', //保险公司id
					insCompanyName: '', //保险公司name
					isReturnRepair: '', //是否返修
					isReturnRepairName: '', //是否返修name
					repairProvinceName: '', //出险省名字
					repairProvince: '', //出险省id
					regionCode: '', //出险省接口id
					repairCityName: '', //出险市名字
					repairCity: '', //出险市id
					repairAddress: '', //出险地点
					clueCreatePerson: '', //线索创建人
					clueType: '', //线索类型
					isInStore: '', //是否到店
					isInStoreName: '', //是否到店name
					clueRemark: '', //备注
					// clueType: '', //线索类型、
					reportNo: "",
					sourcesClues: "",
					sourcesCluesId: ""
				},
				fileList1: [],
				documentId: '',
				listClueType: [{
					id: 1,
					name: "外拓"
				}, {
					id: 2,
					name: "留修且外拓"
				}, {
					id: 0,
					name: "留修"
				}, {
					id: 3,
					name: "客户主动联系"
				}],
				actions: [{
						id: 1,
						name: '男',
					},
					{
						id: 0,
						name: '女',
					}
				],
				type: [{
						id: 1,
						name: '是',
					},
					{
						id: 0,
						name: '否',
					}
				],
				listClueSources: [{
					id: 1,
					name: "保险公司"
				}, {
					id: 2,
					name: "挪车码"
				}, {
					id: 3,
					name: "泰爱车小程序"
				}, {
					id: 4,
					name: "传统渠道资源"
				}, {
					id: 5,
					name: "客户主动联系"
				}, {
					id: 6,
					name: "其他"
				}],

				typeRepair: [{
					id: 1,
					name: "返修"
				}, {
					id: 0,
					name: "送修"
				}],


				rules: {
					'receiveMsgDateString': {
						type: 'string',
						required: true,
						message: '请填写接收信息时间',
						trigger: ['blur', 'change']
					},
					'repairAddress': {
						type: 'string',
						required: true,
						message: '请填写出险地点',
						trigger: ['blur', 'change']
					},
					'repairDateString': {
						type: 'string',
						required: true,
						message: '请填写出险时间',
						trigger: ['blur', 'change']
					},
					'reportPerson': {
						type: 'string',
						required: true,
						message: '请填写报案人',
						trigger: ['blur', 'change']
					},
					'carId': {
						type: 'string',
						required: true,
						message: '请填写车牌号',
						trigger: ['blur', 'change']
					},
					'clueType': {
						type: 'string',
						required: true,
						message: '请选择类型',
						trigger: ['blur', 'change']
					},
					'insCompanyName': {
						type: 'string',
						required: true,
						message: '请选择保险公司',
						trigger: ['blur', 'change']
					},


					'sourcesClues': {
						type: 'string',
						required: true,
						message: '请选择线索来源',
						trigger: ['blur', 'change']
					},

					'phone': [{
							required: true,
							max: 11,
							min: 11,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							validator: phoneRule,
							message: "手机号格式不正确",
							trigger: ['blur', 'change'],
						},
					]
				},

			};
		},
		//如果是自己封装的组件就是mounted() 
		//如果不是组件就是onReady()
		onReady() {
			this.$refs.Fform.setRules(this.rules);
		},
		watch: {
			documentId(val, oldval) {
				if (val != oldval && oldval != '') {
					this.userInfo.repairCityName = ''
					this.userInfo.repairCity = ''
				}
			}

		},

		methods: {

			insCompanyIdModel(id) {
				if (id == 3 && this.userInfo.regionCode == '') {
					uni.$u.toast('请先绑定出险省')
					return
				}
				//保险公司
				uni.navigateTo({
					url: '/pagesA/index/brand?id=' + id + '&regionCode=' + this.userInfo.regionCode
				})

			},
			validatePhone: (val) => {
				return /^1[3456789]\d{9}$/.test(val);
			},
			//出险时间
			confirmOccurrence(E) {
				this.occurrenceModel = false
				this.userInfo.repairDateString = E[0]
				this.$refs.Fform.validateField('repairDateString')
			},
			confirmReceiveMsgDate(E) {
				this.receiveMsgDateModel = false
				this.userInfo.receiveMsgDateString = E[0]
				this.$refs.Fform.validateField('receiveMsgDateString')
			},
			//图片超过大小时取消上传
			oversize(e) {
				this.$u.toast("请传2MB以内大小的图片！");
				return false;
			},

			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.imgBase64(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: lists[i].url,
						urlBase: result

					}))
					fileListLen++
					console.log(this.fileList1)


				}
			},
			imgBase64(url) {
				var that = this
				return new Promise((resolve, reject) => {
					uni.compressImage({
						src: url,
						quality: 40,
						success: res => {
							pathToBase64(res.tempFilePath)
								.then(base64 => {
									resolve(base64)
								})
						}
					})
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},


			submit() {
				var that = this

				this.$refs.Fform.validate().then(res => {

					var base64img = []
					if (uni.$u.test.isEmpty(that.fileList1)) {
						that.$refs.uToast.error('请完善图片必填项!')
						return false
					} else {
						that.fileList1.forEach(obj => {
							base64img.push(obj.urlBase);
						});

						if (base64img.length != 0) {
							that.userInfo.base64img = base64img.toString()
						} 

						wx.requestSubscribeMessage({
							tmplIds: ['oRkx3fcAnHG__A798VgSbhpTFzX1RhN94-huKnmXqVI'],
							success(res) {
								that.getSub()
							},
							fail(res) {
								that.getSub()
							}
						})
					}









				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},
			/* 	imgSY() {
					var that = this
					return new Promise((resolve, reject) => {
						for (let i = 0; i < that.fileList1.length; i++) {
							uni.compressImage({
								src: that.fileList1[i].url,
								quality: 50,
								success: res => {
									pathToBase64(res.tempFilePath)
										.then(base64 => {
											resolve(newImgListN.push(base64))
										})
								}
							})
						}

					})
				}, */
			async getSub() {
				var that = this


				uni.showLoading({
					title: '加载中',
					mask: true,
					icon: 'loading',
				});




				this.$request('saveClue',
					that.userInfo, 'post', {
						"Content-Type": 'application/json',
						"userCode": uni.getStorageSync('changeUserList').userCode,
						"companyCode": store.state.userList.companyCode
					}).then(r => {
					if (r.code == 200) {
						that.$refs.uToast.success(`${r.message}`)
						setTimeout(function() {
							uni.switchTab({
								url: '/pages/sys/msg/index'
							})
						}, 1000)
					} else {
						that.$refs.uToast.error(`${r.message}`)
					}
					uni.hideLoading();
				})


			},
			sexSelect(e) {
				this.userInfo.sex = e.id
				this.userInfo.sexName = e.name

			},

			clueTypeSelect(e) {
				// this.userInfo.sex = e.id
				this.userInfo.clueType = e.name
				this.$refs.Fform.validateField('clueType')
			},
			isReturnRepairSelect(e) {
				this.userInfo.isReturnRepair = e.id
				this.userInfo.isReturnRepairName = e.name

			},
			isInStoreSelect(e) {
				this.userInfo.isInStore = e.id
				this.userInfo.isInStoreName = e.name
			},

			sourcesCluesSelect(e) {
				this.userInfo.sourcesClues = e.name
				this.userInfo.sourcesCluesId = e.id


				this.$refs.Fform.validateField('sourcesClues')
			},
			getUser(msg) {
				this.userInfo.carId = ''
				if (msg.value == 1) {
					this.userInfo.isNewEnergy = 7
				} else {
					this.userInfo.isNewEnergy = 8
				}
			},
			setPlate(plate) {
				if (plate.length >= 7) this.userInfo.carId = plate;
				this.plateShow = false;
				this.$refs.Fform.validateField('carId')
			},
		},
		watch: {
			'userInfo.insCompanyName'(newValue, oldValue) {
				if (newValue) {
					this.$refs.Fform.validateField('insCompanyName')
				}
			},
		},
		onLoad() {
			// 	console.log(store.state.userListName
			// )

			// console.log(store.state.userListName)

			// this.$request('getCluePerson', {companyCode: 361}, 'get', ).then(res => {


			// })







			userData.companyCode = store.state.userList.companyCode, //门店键
				userData.userCode = store.state.userListName.userCode, //门店键
				userData.clueCreatePerson = store.state.userListName.userName


		},
		onShow() {

			this.userInfo.companyCode = store.state.userList.companyCode, //门店键
				this.userInfo.userCode = store.state.userListName.userCode, //门店键
				this.userInfo.clueCreatePerson = store.state.userListName.userName


		},
		onTabItemTap: function(item) {
			this.userInfo.companyCode = store.state.userList.companyCode, //门店键
				this.userInfo.userCode = store.state.userListName.userCode, //门店键
				this.userInfo.clueCreatePerson = store.state.userListName.userName
			this.userInfo = JSON.parse(JSON.stringify(userData))
			this.fileList1 = []
		}
	};
</script>
<style>
	.page {
		padding: 10rpx 20rpx;
		box-sizing: border-box;
	}
</style>